package com.topdt.jbpm.form;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.thx.common.spring.BeanFactory;
import com.thx.common.util.AppContext;
import com.topdt.jbpm.form.FormUI.UIType;
import com.topdt.jbpm.model.Application;
import com.topdt.jbpm.model.ApplyCar;
import com.topdt.jbpm.model.Control;
import com.topdt.jbpm.model.Form;
import com.topdt.jbpm.model.Work;
import com.topdt.jbpm.service.ApplyCarService;
import com.topdt.jbpm.utils.FreeMakerUtils;

import freemarker.template.Template;
import freemarker.template.TemplateException;


/**  
 *  @Project       : saasoa
 *  @Program Name  : com.topdt.jbpm.form.ApplyCarHandle.java
 *  @Class Name    : ApplyCarHandle
 *  @Description   : 申请用车表单处理
 *  @Author        : calonlan
 *  @Creation Date : 2015年2月14日 上午11:28:19 
 *  @ModificationHistory  
 *  Who        When          What 
 *  --------   ----------    -----------------------------------
 *  username   2015年2月14日       TODO
 */
public class ApplyCarHandle extends AbstractCustomFormHandle{

	@Override
	public Document convert2Doc(Map<String, String[]> parameter) {
		Map<String, String> resultMap = new HashMap<String, String>();
		for (String key : parameter.keySet()) {
			String[] values = parameter.get(key);
			if (values.length > 1) {
				String obj = "";
				for (String s : values) {
					obj += s + ";";
				}
				resultMap.put(key, obj.substring(0, obj.length() - 1));
			} else if (values.length > 0) {
				resultMap.put(key, values[0]);
			}
		}
		ApplyCar applyCar = new ApplyCar();
		try {
			applyCar.setApplyCarType((String)resultMap.get("applyCarType"));
			applyCar.setApplyCarUser((String)resultMap.get("applyCarUser"));
			applyCar.setDestination((String)resultMap.get("destination"));
			applyCar.setDriver((String)resultMap.get("driver"));
			applyCar.setEndDate((String)resultMap.get("endDate"));
			applyCar.setIsReturnCar((String)resultMap.get("isReturnCar"));
			applyCar.setReason((String)resultMap.get("reason"));
			applyCar.setReturnCarDate((String)resultMap.get("returnCarDate"));
			applyCar.setStartDate((String)resultMap.get("startDate"));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return applyCar;
	}

	@Override
	public Document getDocument(String workId) {
		ApplyCarService applyCarService = (ApplyCarService) BeanFactory.getBean("applyCarService");
		List<ApplyCar> applyCars = applyCarService.findApplyCarsByWorkId(workId);
		ApplyCar applyCar = null;
		if (applyCars.size() > 0) {
			applyCar = applyCars.get(0);
		} else {
			applyCar = new ApplyCar();
			applyCar.setDocId(workId);
		}
		
		return applyCar;
	}

	@Override
	public void deleteDoc(String documentId) {
		//TODO
		/*FormInstanceDao dao = (FormInstanceDao) SysContext.getBean("formInstanceDao");
		dao.deleteById(documentId);*/
	}

	@Override
	protected Document saveDoc(Document doc) {
		//保存或者更新业务表单
		ApplyCar applyCar = (ApplyCar)doc;
		String workId = applyCar.getDocId();
		ApplyCarService applyCarService = (ApplyCarService) BeanFactory.getBean("applyCarService");
		List<ApplyCar> applyCars = applyCarService.findApplyCarsByWorkId(workId);
		if (applyCars.size() <= 0) {
			applyCar.setCompanyId(AppContext.getCurrentComId());
			applyCarService.save(applyCar);
		} else {
			ApplyCar old = applyCars.get(0);
			try {
				old.setApplyCarType(applyCar.getApplyCarType());
				old.setApplyCarUser(applyCar.getApplyCarUser());
				old.setDestination(applyCar.getDestination());
				old.setDriver(applyCar.getDriver());
				old.setEndDate(applyCar.getEndDate());
				old.setIsReturnCar(applyCar.getIsReturnCar());
				old.setReason(applyCar.getReason());
				old.setReturnCarDate(applyCar.getReturnCarDate());
				old.setStartDate(applyCar.getStartDate());
				old.setApplyCarDay(applyCar.getApplyCarDay());
//				old.setWorkId(workId);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			applyCarService.update(old);
		}
		return applyCar;
	}
	
	
	/** 
	 *  @Description    : 根据业务数据生成html字符串
	 *  @Method_Name    : generateFormHTML
	 *  @param applyCar
	 *  @return 
	 *  @return         : String
	 *  @Creation Date  : 2015年2月28日 下午4:08:43 
	 *  @version        : v1.00
	 *  @Author         : calonlan
	 
	 *  @Update Date    : 2015年2月28日 下午4:08:43 
	 *  @Update Author  : calonlan
	 */
	private String generateFormHTML(ApplyCar applyCar) {
		StringBuffer html = new StringBuffer();
		html.append("<table cellspacing=\"0\"><tbody>");
		html.append("<tr><td>"
					+ "<div class=\"item\" style=\"${fp_applyCarUser.show!''}\">"
						+ "<div class=\"item-label\">"
							+ "<label>申请人</label>"
						+ "</div>"
						+ "<div class=\"item-data\">"
							+ "<input name=\"applyCarUser\" class=\"easyui-validatebox ${fp_applyCarUser.readonly!''}\" "
								+ "style=\"width: 284px; height: 25px;\" required=\"true\" type=\"text\" value=\""+applyCar.getApplyCarUser()+"\" missingmessage=\"申请人不可以为空！\"/>"
						+ "</div>"
					+ "</div></td>");
		html.append("<td>"
				+ "<div class=\"item\" style=\"${fp_applyCarType.show!''}\">"
					+ "<div class=\"item-label\">"
						+ "<label>申请类型</label>"
					+ "</div>"
					+ "<div class=\"item-data\">"
						+ "<input name=\"applyCarType\" class=\"easyui-validatebox ${fp_applyCarType.readonly!\"\"}\" "
							+ "style=\"width: 284px; height: 25px;\" required=\"true\" type=\"text\" value=\""+applyCar.getApplyCarType()+"\" missingmessage=\"申请类型不可以为空！\"/>"
					+ "</div>"
				+ "</div></td></tr>");
		
		html.append("<tr><td>"
				+ "<div class=\"item\" style=\"${fp_startDate.show!''}\">"
					+ "<div class=\"item-label\">"
						+ "<label>开始时间</label>"
					+ "</div>"
					+ "<div class=\"item-data\">"
						+ "<input name=\"startDate\" class=\"easyui-datetimebox ${fp_startDate.readonly!\"\"}\" "
							+ "style=\"width: 284px; height: 25px;\" required=\"true\" type=\"text\" value=\""+applyCar.getStartDate()+"\" missingmessage=\"开始时间不可以为空！\"/>"
					+ "</div>"
				+ "</div></td>");
		html.append("<td>"
				+ "<div class=\"item\" style=\"${fp_endDate.show!''}\">"
					+ "<div class=\"item-label\">"
						+ "<label>结束时间</label>"
					+ "</div>"
					+ "<div class=\"item-data\">"
						+ "<input name=\"endDate\" class=\"easyui-datetimebox ${fp_endDate.readonly!\"\"}\" "
							+ "style=\"width: 284px; height: 25px;\" required=\"true\" type=\"text\" value=\""+applyCar.getEndDate()+"\" missingmessage=\"结束时间不可以为空！\"/>"
					+ "</div>"
				+ "</div></td></tr>");
		
		html.append("<td>"
				+ "<div class=\"item\" style=\"${fp_isReturnCar.show!''}\">"
					+ "<div class=\"item-label\">"
						+ "<label>是否还车</label>"
					+ "</div>"
					+ "<div class=\"item-data\">"
						+ "<input name=\"isReturnCar\" class=\"easyui-validatebox ${fp_isReturnCar.readonly!\"\"}\" "
							+ "style=\"width: 284px; height: 25px;\" required=\"true\" type=\"text\" value=\""+applyCar.getIsReturnCar()+"\" missingmessage=\"是否还车不可以为空！\"/>"
					+ "</div>"
				+ "</div></td></tr>");
		
		html.append("<td>"
				+ "<div class=\"item\" style=\"${fp_applyCarDay.show!''}\">"
					+ "<div class=\"item-label\">"
						+ "<label>用车天数</label>"
					+ "</div>"
					+ "<div class=\"item-data\">"
						+ "<input name=\"applyCarDay\" class=\"easyui-numberbox ${fp_applyCarDay.readonly!\"\"}\" "
							+ "style=\"width: 284px; height: 25px;\" required=\"true\" type=\"text\" value=\""+applyCar.getApplyCarDay()+"\" missingmessage=\"用车天数不可以为空！\"/>"
					+ "</div>"
				+ "</div></td></tr>");
		
		html.append("</tbody></table>");
		
		return html.toString();
	}


	
	
	@Override
	protected FormUI generateFormUI(Application app, Map<String, String> fieldControl,
			Map<String, String> funControl, Document doc, Map<String, Object> context,
			Work work) {
		
		FormUI ui = new FormUI(fieldControl, funControl, doc);
		ui.setUiType(UIType.textHtml);
		ApplyCar applyCar = (ApplyCar)doc;
		Form form = app.getForm();
		// --获得模板
		Template template = null;
		//获取表单html字符串
		String formHTML = generateFormHTML(applyCar);
		try {
	         if ("file".equals(form.getTempletStorageType())) {
				if(context.get("isView") !=null && (Boolean)context.get("isView")){
					String temp = TemplateCreater.mergeTemplate(formHTML);//--先合并
					String htmlSource = TemplateCreater.getViewHtmlByTemplate(temp);
					template = FreeMakerUtils.getTemplateByForm(htmlSource.getBytes("utf-8"));
				}else{
					String sourceHtml = TemplateCreater.mergeTemplate(formHTML);//--先合并
					template = FreeMakerUtils.getTemplateByForm(sourceHtml.getBytes("UTF8"));
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
			ui.setUiText("模板文件不存在或路径错误！");
			return ui;
		}
		if (template == null) {
			return ui;
		}
		String result = "无显示的内容";
		Writer out = new StringWriter();
		try {
			template.process(context, out);
		} catch (TemplateException e) {
			e.printStackTrace();
			ui.setUiText("模板文件不存在或路径错误！");
			return ui;
		} catch (IOException e) {
			e.printStackTrace();
			ui.setUiText("模板文件不存在或路径错误！");
			return ui;
		}
		result = out.toString();
		ui.setUiText(result);
		
		return ui;
	}

	@Override
	public void executeBusiness(Application app, Work work) {
		// TODO Auto-generated method stub
		
	}
	
}
